package com.download.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {

	private String userName; // FTP 登录用户名
	private String password; // FTP 登录密码
	private String ip; // FTP 服务器地址IP地址
	private int port; // FTP 端口
	private FTPClient ftpClient = null; // FTP 客户端代理

	public FTPUtil(String userName, String password, String ip, int port) {//初始化Ftp 连接服务器数据
		this.userName = userName;
		this.password = password;
		this.ip = ip;
		this.port = port;
	}

	public boolean connectServer() {//ftp连接服务器方法
		boolean flag = true;
		if (ftpClient == null) {
			int reply;
			try {
				ftpClient = new FTPClient();
				ftpClient.setControlEncoding("GBK"); // 文件名乱码,默认ISO8859-1，不支持中文
				ftpClient.setDefaultPort(port);
				ftpClient.connect(ip);
				System.out.println("正在连接服务器" + ip);
				ftpClient.login(userName, password);
				
				System.out.print(ftpClient.getReplyString());
				reply = ftpClient.getReplyCode();
				ftpClient.setDataTimeout(120000);

				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					System.err.println("FTP server refused connection.");
					flag = false;
				}

			} catch (SocketException e) {
				
				e.printStackTrace();
				System.err.println("登录ftp服务器 " + ip + " 失败,连接超时！");
				flag = false;
			} catch (IOException e) {
				e.printStackTrace();
				System.err.println("登录ftp服务器 " + ip + " 失败，FTP服务器无法打开！");
				flag = false;
			}
		}
		System.out.println("登陆ftp服务器成功" + ip);
		return flag;
	}
	
	/**
	 * FTP上传单个文件
	 * remotePath		远程路径
	 * localPath		本地路径
	 * remoteFileName	远程文件名
	 * localFileName	本地生成文件名
	 */
	public boolean upload(String remotePath, String localPath,
			String remoteFileName, String localFileName) {
		FileInputStream fis = null;
		boolean retUp = false;
		try {
			File srcFile = new File(localPath + localFileName);
			fis = new FileInputStream(srcFile);
			// 设置上传目录
			boolean bool = ftpClient.changeWorkingDirectory(remotePath);
			if (!bool) {
				ftpClient.makeDirectory(remotePath);
				ftpClient.changeWorkingDirectory(remotePath);
			}
			ftpClient.setControlEncoding("gb2312");

			// 设置文件类型（二进制）
			ftpClient
					.setFileType(org.apache.commons.net.ftp.FTPClient.BINARY_FILE_TYPE);
			retUp = ftpClient.storeFile(remoteFileName, fis);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
		return retUp;
	}
	
    /**
     * 根据域名获取IP地址
     * @param domainName
     * @return IP地址
     * @throws UnknownHostException 
     */
    public static String getIP(String domainName) throws UnknownHostException{
        InetAddress address = InetAddress.getByName(domainName);
        return address.getHostAddress().toString();
    }
    
    /**
     * 从ftpUrl中获取用户名、密码、ip和端口号。
     * 如：ftp://5:5@dx.dl1234.com:8006/[电影天堂www.dy2018.com]银河护卫队BD中英双字.rmvb
     * @param url
     * @return
     * @throws UnknownHostException 
     */
    private static Object[] getFtpInfoByUrl(String url) throws UnknownHostException {
        // [ftp:, , 5:5@dx.dl1234.com:8006, [电影天堂www.dy2018.com]银河护卫队BD中英双字.rmvb]
        String infoSource = url.split("/")[2];
        //[ 5 ,5@dx.dl1234.com, 8006]
        String username = infoSource.split(":")[0];
        //[ 5, dx.dl1234.com]
        String password = infoSource.split(":")[1].split("@")[0];
        String ip = getIP( infoSource.split(":")[1].split("@")[1]);
        int port = Integer.valueOf(infoSource.split(":")[2]);
        Object[] ftpInfo =  {username, password, ip, port};
        return ftpInfo;
    }
}
